package com.api.user.service.impl;

import com.api.base.dao.UserMapper;
import com.api.base.model.User;
import com.api.common.UtilFun;
import com.api.user.dao.ReferralLogMapper;
import com.api.user.model.ReferralLog;
import com.api.user.service.ReferralLogService;
import com.api.core.service.AbstractService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.github.pagehelper.PageInfo;

/**
 * Created by wanghuiwen on 2022/05/11.
 */
@Service
@Transactional
public class ReferralLogServiceImpl extends AbstractService<ReferralLog> implements ReferralLogService {
    @Resource
    private ReferralLogMapper referralLogMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public Result list(Long id, Integer page, Integer size){
        PageHelper.startPage(page, size);
        List<Map<String, Object>> res = referralLogMapper.list(id);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(res);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @Override
    public Map<String, Object> user(Long id) {
        User user = userMapper.selectByPrimaryKey(id);
        if(user.getReferralCode() == null){
            String referralCode = genReferralCode();
            user.setReferralCode(referralCode);
            userMapper.updateByPrimaryKeySelective(user);
        }
        Map<String, Object> res = new HashMap<>();
        res.put("referralCode",user.getReferralCode());

        BigDecimal receive = referralLogMapper.receive(id);
        BigDecimal friendReceive = referralLogMapper.friendReceive(id);
        res.put("receive",receive);
        res.put("friendReceive",friendReceive);

        return res;
    }

    private String genReferralCode() {
        String referralCode =  UtilFun.getStringRandom(8);
        User oldUser =  userMapper.selectByReferralCode(referralCode);
        if(oldUser != null) return genReferralCode();
        return  referralCode;
    }
}
